package com.northpool.operator.common.groovy.code

import com.northpool.operator.annotation.*
import com.northpool.operator.common.algorithm.OperatorTestBuild
import com.northpool.operator.common.algorithm.TestParamBuilder
import com.northpool.operator.param.ParamTool
import com.northpool.operator.utils.StpOperatorHelper

import java.security.SecureRandom

@OperatorInfo(
        ref = "UUIDOperator",
        name = "UUID生成",
        description = "生成指定长度和间隔符的UUID"
)

@OutputParams([
        @OutputParam(ref = "uuid", name = "生成的UUID")
])
class UUIDTest extends StpOperatorHelper {

    @InputParams([
            @InputParam(ref = "length", name = "生成长度", desc = "随机生成的ID字符串长度 1-256之间", value = "32"),
            @InputParam(ref = "splitChar", name = "间隔符", desc = "ID中的间隔符", value = "-"),
            @InputParam(ref = "prefix", name = "前缀", desc = "填充到随机生成的ID之前", value = ""),
            @InputParam(ref = "suffix", name = "后缀", desc = "填充到随机生成的ID之后", value = ""),
    ])
    UUIDTest() {
    }

    static void main(String[] args) {
        OperatorTestBuild.execute(UUIDTest.class, TestParamBuilder.aBuilder()
                .param("length", "16")
                .param("splitChar", "-")
                .param("prefix", "")
                .param("suffix", "")
                .build())
    }


    @Override
    void execute(ParamTool params) {
        String spitChar = params.getStr("splitChar");
        String lengthStr = params.getStr("length");
        String prefix = params.getStr("prefix");
        String suffix = params.getStr("suffix");

        if (spitChar == null || spitChar.length() != 1) {
            throw new IllegalArgumentException("间隔符必须是一个字符");
        }

        int length = Integer.parseInt(lengthStr);
        if (length <= 0 || length > 256) {
            throw new IllegalArgumentException("生成长度必须在1到256之间");
        }

        // 生成UUID并处理
        SecureRandom random = new SecureRandom();
        StringBuilder uuidBuilder = new StringBuilder();
        for (int i = 0; i < length; i++) {
            int randomInt = random.nextInt(16); // 生成0到15之间的随机数
            uuidBuilder.append(Integer.toHexString(randomInt)); // 转换为十六进制字符
        }

        String uuidStr = uuidBuilder.toString();

        // 插入间隔符
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < uuidStr.length(); i++) {
            sb.append(uuidStr.charAt(i));
            if ((i + 1) % 8 == 0 && i + 1 < uuidStr.length()) {
                sb.append(spitChar);
            }
        }

        this.result("uuid", prefix + sb + suffix);
    }
}
